//
//  FB+Rx.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/20.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import FBSDKLoginKit
import RxSwift

extension Reactive where Base == LoginManager {
    
    func login(permissions: [String], from viewController: UIViewController?) -> Single<LoginManagerLoginResult> {
        return Single.create{ [weak base] single -> Disposable in
            base?.logIn(permissions: permissions, from: viewController, handler: { (result, error) in
                if let result = result {
                    if result.isCancelled {
                        single(.error(NullError()))
                    } else {
                        single(.success(result))
                    }
                } else if let error = error {
                    single(.error(error))
                } else {
                    single(.error(NullError()))
                }
            })
            return Disposables.create {
            }
        }
    }
    
}

extension Reactive where Base == GraphRequest {
    
    static func start(graphPath: String, parameters: [String: Any], method: HTTPMethod) -> Single<Any> {
        return Single.create { (single) -> Disposable in
            let api = Base.init(graphPath: graphPath, parameters: parameters, httpMethod: method)
            api.start(completionHandler: { (_, result, error) in
                if let result = result {
                    single(.success(result))
                } else if let error = error {
                    single(.error(error))
                } else {
                    single(.error(NullError()))
                }
            })
            return Disposables.create()
        }
    }
    
}
